package com.designoutput.ui.gallery
{
	import com.designoutput.design.search.HolderDropdown;
	import com.designoutput.design.search.SearchBar;
	import com.designoutput.design.search.SearchResult;
	import com.designoutput.ui.GalleryCanvas;
	import com.designoutput.utils.Globals;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.ui.Keyboard;

	public class GallerySearchBar extends Sprite
	{
		private var parentCanvas:GalleryCanvas;
		public var currentTerm:String;
		public var maxresults:Number = 15; // The number to indicate the max element to show on the drop down list
		public var highlighted:int;
		public var xml:XML;
		public var wordlist:XMLList;
		public var searchactive:Boolean;
		public var counter:Number;

		public var search:SearchBar; // the init bar to show to type in key words
		public var holder:HolderDropdown; // the holder contains the result list
		public var resultcon:Sprite; // to persist the result array temporarily. 

		public function GallerySearchBar(parentCanvas:GalleryCanvas)
		{
			this.parentCanvas = parentCanvas;
			
			search = new SearchBar;
			search.x = search.y = 0;
			search.textBox.text = "";
			addChild(search);
			
			counter = 0;
			searchactive = false;
			highlighted = -1;
			
			holder = new HolderDropdown();
			holder.x = search.x + 4;
			holder.y = search.y + search.height / 2;
			addChildAt(holder, 0);
			holder.bg.visible = false;

			resultcon = new Sprite;
			resultcon.x = 1;
			resultcon.y = 11;
			holder.addChild(resultcon);

			search.searchbut.buttonMode = true;
			search.searchbut.gotoAndStop(3);
			search.searchbut.addEventListener(MouseEvent.ROLL_OVER, rolloverSearch);
			search.searchbut.addEventListener(MouseEvent.ROLL_OUT, rolloverSearch);
			search.searchbut.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownSearch);
			search.searchbut.addEventListener(MouseEvent.MOUSE_UP, mouseUpSearch);
			search.textBox.addEventListener(FocusEvent.FOCUS_IN, searchTextBox_focusInHandler, false, 0, true);
			search.textBox.addEventListener(FocusEvent.FOCUS_OUT, searchTextBox_focusOutHandler, false, 0, true);
			search.textBox.addEventListener(KeyboardEvent.KEY_DOWN, searchTextBox_keyDownHandler, false, 0, true);
			search.textBox.addEventListener(Event.CHANGE, searchTextBox_changeHandler, false, 0, true);
		}
		
		public function xmlloaded(event:Event):void
		{
			xml = new XML(event.currentTarget.data);
//			trace(xml);
			wordlist = xml.word; // xml -> <terms> root node
		}
		
		public function dataLoaded(data:XML):void{
			xml = data;
			wordlist = new XMLList(xml.word); 
		}

		public function rolloverSearch(event:MouseEvent):void
		{
			event.currentTarget.gotoAndStop(2);
		}
		
		public function rollOutSearch(event:MouseEvent):void
		{
			event.currentTarget.gotoAndStop(1);
		}

		public function mouseUpSearch(event:MouseEvent):void
		{
			event.currentTarget.gotoAndStop(2);
		}

		public function mouseDownSearch(event:MouseEvent):void
		{
			event.currentTarget.gotoAndStop(3);
			this.parentCanvas.searchGallery(search.textBox.text);
		}

		protected function searchTextBox_focusInHandler(event:FocusEvent):void {
			updatePromptVisibility();
			updateSearchResults();
		}
		
		public function searchTextBox_focusOutHandler(event:FocusEvent):void
		{
			updatePromptVisibility();
			if(Globals.focusManager.focus == null || !this.contains(Globals.focusManager.focus))
				closeSearchResult();
		}
		
		protected function updatePromptVisibility():void {
			search.dummy.visible = search.textBox.text == "" && stage.focus != search.textBox;
		}
		
		protected function searchTextBox_keyDownHandler(event:KeyboardEvent):void {		
			var result:SearchResult;
			
			if(searchactive){			
				if (event.keyCode == Keyboard.DOWN)
				{
					highlighted++;
					if (highlighted > resultcon.numChildren - 1)
						highlighted=0;
	
					updateHighlight();
				}
				
				if (event.keyCode == Keyboard.UP)
				{
					highlighted--;
					if (highlighted < 0)
						highlighted = resultcon.numChildren - 1;
	
					updateHighlight();
				}
			}
			
			if(event.keyCode == Keyboard.ENTER){
				if(highlighted == -1)
					this.parentCanvas.searchGallery(search.textBox.text);
				else
					selectHighlightedResult();
			}
		}
		
		protected function searchTextBox_changeHandler(event:Event):void {
			updatePromptVisibility();
			updateSearchResults();
		}
		
		public function updateSearchResults():void
		{
			closeSearchResult();
			
			if(search.textBox.text == "" || search.textBox.text == " ")
				return;
			
			var result:SearchResult = null;

			counter=0;
			var targetText:RegExp = new RegExp("^" + search.textBox.text, "/i");
			var i:int=0;
			while (i < wordlist.length())
			{
				if (targetText.test(wordlist[i]) == true && counter != maxresults)
				{
					result = new SearchResult();
					result.tb.text = wordlist[i];
					result.term = wordlist[i]; // not sure term?????????
					result.y = counter * result.height;
					result.addEventListener(MouseEvent.ROLL_OVER, result_rollOverHandler, false, 0, true);
					result.addEventListener(MouseEvent.CLICK, result_clickHandler, false, 0, true);
					result.mouseChildren = false;
					result.buttonMode = true;
					resultcon.addChild(result);
					counter++;
				}
				i++;
			}
			if (counter > 0)
			{
				highlighted = -1;
				searchactive = true;
				holder.visible = true;
				holder.bg.visible = true;
				holder.bg.height = resultcon.height + 25;
				
				updateHighlight();
			}
		}
		
		protected function updateHighlight():void {
			for(var i:int = 0; i< resultcon.numChildren; i++){
				var result:SearchResult = resultcon.getChildAt(i) as SearchResult;
				
				if(i == highlighted){
					result.gotoAndStop(2);
				} else {
					result.gotoAndStop(1);
				}
			}
		}
		
		protected function closeSearchResult():void {
			while (resultcon.numChildren > 0)
				resultcon.removeChildAt(0);
			
			searchactive = false;
			holder.visible = false;
			holder.bg.visible = false;
			highlighted = -1;
			counter = 0;
		}
		
		protected function selectHighlightedResult():void {
			var result:SearchResult = resultcon.getChildAt(highlighted) as SearchResult;
			search.textBox.text = result.term;
			closeSearchResult();
		}
		
		protected function result_rollOverHandler(e:MouseEvent):void {
			var index:int = resultcon.getChildIndex(e.currentTarget as DisplayObject);
			highlighted = index;
			updateHighlight();
		}

		protected function result_clickHandler(e:MouseEvent):void
		{
			var index:int = resultcon.getChildIndex(e.currentTarget as DisplayObject);
			highlighted = index;
			selectHighlightedResult();
		}
	}
}